import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';
import { t } from '@lingui/macro';

export default class RegionStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  cities = [];
  _cityId = '';
  regions = [];
  loading = false;
  _city = {};

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  * fetchCities() {
    this.loading = true;
    try {
      const cities = yield api.cities();
      this.cities = cities.sort((a, b) => a.itemId.localeCompare(b.itemId));
      const idx = this.cities.findIndex((c) => c.itemId === this._cityId);
      if (idx === -1) this.cityId = this.cities[0].itemId; // 初始化或当前城市被删除后,重新获取区域
    } finally {
      this.loading = false;
    }
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    if (!this._cityId) return;
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count(this._cityId, { search });
      const regions = yield api.search(this._cityId, { search, pg });
      this.regions = regions.map((p) => ({ ...p, disabled: !p.disabled }));
    } finally {
      this.loading = false;
    }
  }

  * get(id) {
    const res = yield api.get(id);
    return observable(res);
  }

  * _reload(cause) {
    const isCity = !cause.parentId;
    if (isCity) {
      yield this.fetchCities();
    } else {
      yield this.query();
    }
  }

  * update(region) {
    yield api.update(region);
    yield this._reload(region);
  }

  * create(region) {
    yield api.create(region);
    yield this._reload(region);
  }

  * remove(region) {
    yield api.remove(region.itemId);
    yield this._reload(region);
  }

  * updateState(region) {
    const { itemId, disabled } = region;
    yield api.update({ itemId, disabled });
    yield this.query();
  }

  * nextId(parentId) {
    return yield api.nextId(parentId);
  }

  async existsValidator(rule, value) {
    if (!value) return Promise.resolve();
    try {
      const item = await api.get(value); // 注意get不存在时会抛出404异常
      if (item) return Promise.reject(new Error(t`${value}已存在`));
    } catch (_) {
      return Promise.resolve();
    }
  }

  get city() {
    return this.cities.find((item) => item.itemId === this.cityId);
  }

  * allRegions(maxLevel) {
    const res = yield api.allRegions(maxLevel);
    const city = res.filter((p) => p.itemId.length === 3) || [];
    this._city = city.reduce((acc, cur) => {
      const { name, itemId } = cur;
      acc[itemId] = name;
      return acc;
    }, {}) || {};
  }

  get cityId() { return this._cityId; }

  set cityId(cityId) {
    this._cityId = cityId;
    this.query();
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
    // _.mergeWith(this._args.pg, pg, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }


}
